import axios,{AxiosError,AxiosResponse,InternalAxiosRequestConfig} from 'axios'
import {getToken,token_prefix} from './token'
import { ElMessage } from 'element-plus'
import useStore from '@/store/'
import config from './config'
const baseURL = config.baseURL

const request = axios.create({
    baseURL: baseURL,
    // timeout:3000,
    headers:{
        "Content-Type":"application/json;charset=UTF-8",
    },
});


//请求拦截器
request.interceptors.request.use(
    (config: InternalAxiosRequestConfig)=>{
        if(getToken()){
            config.headers["Authorization"] = token_prefix + getToken();
        }
            return config;
    },  
    (error:AxiosError) => {
        return Promise.reject(error);
    }
);

//配置响应拦截器

request.interceptors.response.use(
    (response: AxiosResponse) => {
        switch (response.data.code){
            case -1:
                ElMessage.error(response.data.msg)
                break;
            case 400:
                ElMessage.error(response.data.msg);
                break;
            case 402:
                const { user } = useStore();
                ElMessage.error(response.data.msg);
                break;
            case 500:
                ElMessage.error(response.data.msg);
                break;
        }
        return response;
    },
    (error: AxiosError) => {
        let {message}  =  error;
        if(message == "Network Error"){
            message  = "网络异常";
        }else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substring(message.length - 3) + "异常";
        }
          ElMessage({ message: message, type: "error", duration: 5000 });
          return Promise.reject(error);
    }
);

export default  request;